/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.csit.iap.ws;

import com.csit.iap.client.BranchClientServlet;
import com.csit.iap.domain.BookStore;
import com.itextpdf.text.DocumentException;
import java.io.FileNotFoundException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;

/**
 *
 * @author Kundzia
 */
@WebService(serviceName = "MobileClientWS")
public class MobileClientWS {

    /**
     * Web service operation
     */
    @WebMethod(operationName = "login")
    public String login(@WebParam(name = "username") String username, @WebParam(name = "password") String password) {
        try {
            Class.forName("org.apache.derby.jdbc.ClientDriver");
            Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/BookStoreChainHQDB", "admin", "admin");
            con.setAutoCommit(false);
            PreparedStatement stmt = con.prepareStatement("select id, username from EMPLOYEE where username=? and password=?");
            stmt.setString(1, username);
            stmt.setString(2, password);
            ResultSet res = stmt.executeQuery();
            
            if (res.next()) {
                String ret = UUID.randomUUID().toString();
                
                PreparedStatement stmt_up = con.prepareStatement("update EMPLOYEE set access_key=?, access_date=? where id=?");
                stmt_up.setString(1, ret);
                stmt_up.setTimestamp(2, new Timestamp(System.currentTimeMillis() + 1800000));
                stmt_up.setInt(3, res.getInt("id"));
                stmt_up.executeUpdate();
                
                stmt_up.close();
                
                res.close();
                stmt.close();
                con.commit();
                con.close();
                return ret;
            } else {
                res.close();
                stmt.close();;
                con.close();
                throw new IllegalArgumentException("Wrong username or password");
            }     
            
        } catch (SQLException ex) {
            throw new RuntimeException(ex.toString());
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException(ex.toString());
        } catch (Exception ex) {
            throw new RuntimeException(ex.toString());
        }
        
    }

    /**
     * Web service operation
     */
    @WebMethod(operationName = "getBookStoreReport")
    public String getBookStoreReport(@WebParam(name = "bookstore_id") int bookstore_id, String accesskey) {
        try {
            Class.forName("org.apache.derby.jdbc.ClientDriver");
            Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/BookStoreChainHQDB", "admin", "admin");
            con.setAutoCommit(false);
            PreparedStatement stmt = con.prepareStatement("select id, access_date from EMPLOYEE where access_key=?");
            stmt.setString(1, accesskey);
            ResultSet res = stmt.executeQuery();
            
            BranchClientServlet client = new BranchClientServlet();
            
            if (res.next() && res.getTimestamp("access_date").after(new Timestamp(System.currentTimeMillis()))) {
                PreparedStatement stmt_up = con.prepareStatement("update EMPLOYEE set access_date=? where id=?");
                stmt_up.setTimestamp(1, new Timestamp(System.currentTimeMillis() + 1800000));
                stmt_up.setInt(2, res.getInt("id"));
                stmt_up.executeUpdate();
                
                stmt_up.close();
                res.close();
                stmt.close();
                con.commit();
                con.close();
                return "http://"+client.askForReport(bookstore_id);
                
            } else {
                res.close();
                stmt.close();
                con.close();
                throw new IllegalArgumentException("Wrong user data. Probably your access has expired. Try to log in again");
            }            
        } catch (DocumentException ex) {
           throw new RuntimeException(ex.toString());
        } catch (FileNotFoundException ex) {
            throw new RuntimeException(ex.toString());
        } catch (SQLException ex) {
            throw new RuntimeException(ex.toString());
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException(ex.toString());
        } 
    }
    
    @WebMethod(operationName = "showChainBookStores")
    public List<BookStore> showChainBookStores() {        
        try {
            Class.forName("org.apache.derby.jdbc.ClientDriver");
            Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/BookStoreChainHQDB", "admin", "admin");
            PreparedStatement stmt = con.prepareStatement("select * from BOOKSTORE");
            ResultSet res = stmt.executeQuery();
            List<BookStore> bookstores = new ArrayList<BookStore>();
            
            while (res.next()) {
                BookStore bStore = new BookStore();
                bStore.setId(res.getInt("id"));
                bStore.setAddress(res.getString("address"));
                bookstores.add(bStore);
            }
            
            res.close();
            stmt.close();
            con.close();
            
            return bookstores;
        } catch (SQLException ex) {
            throw new RuntimeException(ex.toString());
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException(ex.toString());
        } catch (Exception ex) {
            throw new RuntimeException(ex.toString());
        }        
    }
}
